<?php

namespace App\Http\Controllers\Admin\Question;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Requests\Admin\Question\Tag\CreateRequest;
use App\Http\Requests\Admin\Question\Tag\UpdateRequest;
use App\Models\QuestionTag;
use App\Repositories\Admin\Question\TagRepository;
use Illuminate\Http\Request;

class TagController extends BaseController
{

    /**
     * TagController constructor.
     */
    public function __construct()
    {
        $this->repo = new TagRepository();
    }

    /**
     * 获取列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetchList(Request $request)
    {
        $data = $this->repo->pagination();
        return $this->success($data);
    }

    /**
     * 查单个信息
     * @param QuestionTag $tag
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetchInfo(QuestionTag $tag)
    {
        return $this->success($tag);
    }

    /**
     * 创建
     * @param CreateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(CreateRequest $request)
    {
        $name = $request->get('name');
        $tag = $this->repo->create($name);
        return !$tag ? $this->error('添加失败') : $this->success($tag, '添加成功');
    }

    /**
     * 更新标签
     * @param UpdateRequest $request
     * @param QuestionTag $tag
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UpdateRequest $request, QuestionTag $tag)
    {
        $name = $request->get('name');
        $tag = $this->repo->update($tag, ['name' => $name]);
        return !$tag ? $this->error('更新失败') : $this->success($tag, '更新成功');
    }

    /**
     * 删除
     * @param QuestionTag $tag
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delete(QuestionTag $tag)
    {
        return $tag->delete() ? $this->success([], '删除成功') : $this->error('更新失败');
    }
}
